﻿#include "filestatistics.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tableWidget->setColumnCount(4);
    ui->tableWidget->setHorizontalHeaderLabels({"File Path", "Lines", "Characters", "Type"});
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_chooseFoldersButton_clicked()
{
    bool done = false;
    while (!done) {
        QString folder = QFileDialog::getExistingDirectory(this, "Select Directory", QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
        if (folder.isEmpty()) {
            done = true;
        } else {
            folders.append(QDir(folder));
        }
    }
}

void MainWindow::on_calculateButton_clicked()
{
    if (folders.isEmpty()) {
        QMessageBox::warning(this, "Warning", "Please select at least one folder.");
        return;
    }

    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    int totalLines = 0;
    int totalChars = 0;

    for (const auto &folder : folders) {
        FileStatistics stats(folder);
        const auto &results = stats.getResults();

        for (const auto &result : results) {
            int row = ui->tableWidget->rowCount();
            ui->tableWidget->insertRow(row);
            ui->tableWidget->setItem(row, 0, new QTableWidgetItem(result.filePath));
            ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(result.lines)));
            ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(result.characters)));
            ui->tableWidget->setItem(row, 3, new QTableWidgetItem(result.type));

            totalLines += result.lines;
            totalChars += result.characters;
        }
    }

    ui->tableWidget->insertRow(ui->tableWidget->rowCount());
    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, new QTableWidgetItem("Total"));
    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, new QTableWidgetItem(QString::number(totalLines)));
    ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, new QTableWidgetItem(QString::number(totalChars)));
}
